using System.ComponentModel.DataAnnotations;
using Identity.Application.Contracts.Requests.UserRoles;
using Identity.Application.UserRoles.Commands;
using Identity.HttpAPI.Permission;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Identity.HttpAPI.Controllers
{
    [ApiController]
    [Route("api")]
    public class UserRolesController : ControllerBase
    {
        private readonly IMediator _mediator;

        public UserRolesController(IMediator mediator)
        {
            _mediator = mediator;
        }


        [HttpGet("users/{userId}/roles")]
        [Authorize(Policy = "user:roles:view")]
        [Permission("user:roles:view" , "获取用户所有角色")]
        public async Task<IActionResult> GetUserRoles([FromRoute] Guid userId)
        {
            var command = new GetUserRolesCommand(userId);
            var roles = await _mediator.Send(command);
            return Ok(roles);
        }


        [HttpGet("roles/{roleId}/users")]
        [Authorize(Policy = "role:users:view")]
        [Permission("role:users:view" , "获取赋予该角色的所有用户")]
        public async Task<IActionResult> GetUsersInRole([FromRoute] Guid roleId)
        {
            var command = new GetUsersInRoleCommand(roleId);
            var users = await _mediator.Send(command);
            return Ok(users);
        }


        [HttpPost("users/{userId}/roles")]
        [Authorize(Policy = "user:role:assign")]
        [Permission("user:role:assign" , "赋予用户角色")]
        public async Task<IActionResult> AddRolesToUser(Guid userId, [FromBody] AssignRolesRequest request)
        {
            var command = new AddUserToRoleCommand(userId, request.RoleIds);
            var result = await _mediator.Send(command);
            if (!result.IsSuccess) return BadRequest(result.Errors);
            return Ok();
        }


        [HttpDelete("users/{userId}/roles/{roleId}")]
        [Authorize(Policy = "user:role:remove")]
        [Permission("user:role:remove" , "移除用户角色")]
        public async Task<IActionResult> RemoveRoleFromUser(Guid userId, Guid roleId)
        {
            var command = new RemoveUserFromRoleCommand(userId, roleId);
            var result = await _mediator.Send(command);

            if (!result.IsSuccess) return BadRequest(result.Errors);
            return Ok();
        }


        [HttpPut("users/{userId}/roles")]
        [Authorize(Policy = "user:roles:replace")]
        [Permission("user:roles:replace" , "替换用户所有角色")]
        public async Task<IActionResult> ReplaceUserRoles(Guid userId, [FromBody] AssignRolesRequest request)
        {
            var command = new ReplaceUserRolesCommand(userId, request.RoleIds);
            var result = await _mediator.Send(command);
            if (!result.IsSuccess) return BadRequest(result.Errors);
            return Ok();
        }
    }




}